import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart' ;
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mfkb/config/Config.dart';
import 'package:mfkb/pages/modules/CustomRoute.dart';
import 'package:mfkb/pages/modules/MyDialog.dart';
import 'package:mfkb/pages/modules/Nothing.dart';
import 'package:mfkb/pages/modules/SliderItem.dart';
import 'package:mfkb/pages/school/market/GoodsDetail.dart';
import 'package:mfkb/pages/school/market/Orders.dart';
import 'package:mfkb/pages/school/market/Place.dart';
import 'package:mfkb/plugin/MyBehavior.dart';
import 'package:mfkb/service/MarketService.dart';
import 'package:toast/toast.dart';

class Cart extends StatefulWidget  {
  @override
  _CartState createState() => _CartState();
}

class _CartState extends State<Cart> {

  List<dynamic> _list = null ;
  List<dynamic> _select = [] ;
  bool _all = false ;
  double money = 0;
  bool canPay = false ;
  dynamic def = null ;
  bool _visible = false ;

  @override
  void initState() {
    super.initState();
    MarketService().cartGoods().then((value){
      if(value["code"] == 200){
        _list = value["data"] ;
        for(var i = 0 ; i < _list.length ; i++){
          var temp = {"id":_list[i]["gid"] , "select":false , "count":1} ;
          _select.add(temp) ;
        }
        setState(() { });
      }else{
        Toast.show(value["msg"], context) ;
      }
    }) ;
    MarketService().getDefPlace().then((value){
      print(value) ;
      if(value["code"] == 200){
        def = value["data"] ;
      }else if(value["code"] == 201){
        def = null ;
      }else{
        Toast.show(value["msg"], context) ;
        def = "error" ;
      }
    }) ;
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.dark ,
      child: Scaffold(
        body: Stack(
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Color.fromARGB(255, 252, 252, 252) , Color.fromARGB(255, 246, 246, 248)] ,
                  begin: Alignment.topCenter ,
                  end: Alignment.bottomCenter
                ) ,
              ),
              child: Column(
                children: <Widget>[
                  Container(
                    height: MediaQuery.of(context).padding.top ,
                  ) ,
                  Container(
                    height: 45,
                    child: Row(
                      children: <Widget>[
                        Container(
                          width: 17,
                          height: 17,
                          margin: EdgeInsets.only(left:ScreenUtil().setWidth(19)),
                          child: GestureDetector(
                            child: Container(
                              width: 17,
                              height: 17,
                              child: Image.asset("assets/images/back.png" , fit: BoxFit.fill,),
                            ),
                            onTap: (){
                              Navigator.of(context).pop() ;
                            },
                          ),
                        ) ,
                        Expanded(
                          child: Container(
                            child: Center(
                              child: Text("购物车" , style: TextStyle(
                                color: Color.fromARGB(255, 19 , 28 , 53) ,
                                fontSize: ScreenUtil().setSp(18) ,
                                fontWeight: FontWeight.bold 
                              ),),
                            ),
                          ),
                        ) ,
                        Container(
                          height: 17,
                          width: 36,
                        )
                      ],
                    ),
                  ) ,
                  _list == null ? Expanded(child:Nothing()) : Expanded(
                    child: Container(
                      child: ScrollConfiguration(
                        behavior: MyBehavior() ,
                        child: ListView(
                          padding: EdgeInsets.all(0),
                          children: List.generate(_list.length, (index){
                            return GestureDetector(
                              child: Container(
                                margin: EdgeInsets.only(top:ScreenUtil().setHeight(10) , left:ScreenUtil().setWidth(10) , right:ScreenUtil().setWidth(10) , bottom: ScreenUtil().setHeight(index == _list.length - 1 ? 15 : 0)),
                                width: ScreenUtil().setWidth(110),
                                height: ScreenUtil().setHeight(110),
                                decoration: BoxDecoration(
                                  color: Colors.white ,
                                  borderRadius: BorderRadius.all(Radius.circular(12))
                                ),
                                child: SliderItem(
                                  action: GestureDetector(
                                    child: Container(
                                      width: ScreenUtil().setWidth(50),
                                      decoration: BoxDecoration(
                                        color: Colors.red ,
                                        borderRadius: BorderRadius.only(topRight:Radius.circular(12) , bottomRight: Radius.circular(12))
                                      ),
                                      child: Center(
                                        child: Text(
                                          "删除" , style: TextStyle(
                                            color: Colors.white 
                                          ),
                                        ),
                                      ),
                                    ),  
                                    onTap: (){
                                      showDialog(
                                        context: context ,
                                        builder: (context){
                                          return MyDialog(title: "确定要删除该商品吗？" , yes: (){
                                            print(_list[index]["cid"]) ;
                                            MarketService().deleteGoodsInCart(_list[index]["cid"]).then((value){
                                              if(value["code"] == 200){
                                                _list.removeAt(index) ;
                                              }else{
                                                Toast.show(value["msg"], context) ;
                                              }
                                              setState(() {});
                                            }) ;
                                            Navigator.of(context).pop() ;
                                          },no:(){ }) ;
                                        }
                                      ) ;
                                    },
                                  ) ,
                                  child: Container(
                                    // width: ScreenUtil().setWidth(110),
                                    height: ScreenUtil().setHeight(110),
                                    child: Row(
                                      children: <Widget>[
                                        Container(
                                          margin: EdgeInsets.only(left:ScreenUtil().setWidth(12)),
                                          width: ScreenUtil().setHeight(20),
                                          height: ScreenUtil().setHeight(20),
                                          child: Image.asset(_select[index]["select"] ? "assets/images/selected.png" : "assets/images/un_select.png"),
                                        ) ,
                                        GestureDetector(
                                          child: Container(
                                            width: ScreenUtil().setHeight(80),
                                            height: ScreenUtil().setHeight(80),
                                            margin: EdgeInsets.only(left:ScreenUtil().setWidth(13)),
                                            decoration: BoxDecoration(
                                              borderRadius: BorderRadius.all(Radius.circular(4)) ,
                                              border: Border.all(
                                                color:Color.fromARGB(255, 236, 237, 241)
                                              )
                                            ),
                                            child: CachedNetworkImage(
                                              imageUrl: Config().getImgHost() + _list[index]["icon"],
                                              fit: BoxFit.fill,
                                              placeholder: (contex , url){
                                                return Container(
                                                  color:Color.fromARGB(255, 246, 245, 248) ,
                                                  child: Center(
                                                    child: Image.asset("assets/images/imageloading.png"),
                                                  ) ,
                                                ) ;
                                              }
                                            ),
                                          ),
                                          onTap: (){
                                            Navigator.of(context).push(CustomRoute(GoodsDetail(id:_list[index]["gid"]))) ;
                                          },
                                        ) ,
                                        Expanded(
                                          child: Container(
                                            height: ScreenUtil().setHeight(80) ,
                                            margin: EdgeInsets.only(left:ScreenUtil().setWidth(11) , right:ScreenUtil().setWidth(16)),
                                            child: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: <Widget>[
                                                Container(
                                                  margin: EdgeInsets.only(top:1),
                                                  child: Text(_list[index]["gname"] , maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(
                                                    color: Color.fromARGB(255, 78, 86, 109) ,
                                                    fontSize: ScreenUtil().setSp(14) ,
                                                    fontWeight: FontWeight.bold 
                                                  ),),
                                                ) ,
                                                Container(
                                                  margin: EdgeInsets.only(top:ScreenUtil().setHeight(8)),
                                                  child: Text(_list[index]["sname"] , maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(
                                                    color: Color.fromARGB(255, 121, 132, 155) ,
                                                    fontSize: ScreenUtil().setSp(11) ,
                                                  ),),
                                                ) ,
                                                Container(
                                                  margin: EdgeInsets.only(top:ScreenUtil().setHeight(5)),
                                                  child: Row(
                                                    mainAxisAlignment: MainAxisAlignment.start ,
                                                    crossAxisAlignment: CrossAxisAlignment.end ,
                                                    children: <Widget>[
                                                      Text("￥" , style: TextStyle(
                                                        fontSize: ScreenUtil().setSp(10) ,
                                                        color: Color.fromARGB(255, 19, 28, 53) ,
                                                        fontWeight: FontWeight.bold ,
                                                        height: ScreenUtil().setHeight(15) / ScreenUtil().setSp(10)
                                                      ),textAlign: TextAlign.start,) ,
                                                      Text(_list[index]["price"].toString() , style: TextStyle(
                                                        fontSize: ScreenUtil().setSp(16) ,
                                                        color: Color.fromARGB(255, 19, 28, 53) ,
                                                        fontWeight: FontWeight.bold ,
                                                      ),textAlign: TextAlign.start,) ,
                                                      Expanded(
                                                        child:Container(
                                                          height: ScreenUtil().setHeight(22),
                                                          child: Row(
                                                            mainAxisAlignment: MainAxisAlignment.end ,
                                                            // crossAxisAlignment: CrossAxisAlignment.center,
                                                            children: <Widget>[
                                                              GestureDetector(
                                                                child: Container(
                                                                  width: ScreenUtil().setHeight(22),
                                                                  height: ScreenUtil().setHeight(22),
                                                                  color: Colors.white ,
                                                                  child: Center(
                                                                    child: Container(
                                                                      width: ScreenUtil().setHeight(18),
                                                                      height: ScreenUtil().setHeight(18),
                                                                      decoration: BoxDecoration(
                                                                        color: Color.fromARGB(255, 248, 248, 249) , 
                                                                        borderRadius: BorderRadius.all(Radius.circular(ScreenUtil().setHeight(9)))
                                                                      ),
                                                                      child: Center(
                                                                        child: Text("-" , style: TextStyle(
                                                                          color: _select[index]["count"] == 1 ? Color.fromARGB(255, 205, 207, 221) : Color.fromARGB(255, 19, 28, 53) ,
                                                                          fontWeight: FontWeight.bold 
                                                                        )),
                                                                      ),
                                                                    ),
                                                                  )
                                                                ) ,
                                                                onTap: (){
                                                                  if(_select[index]["count"] <= 1){
                                                                    return ;
                                                                  }else{
                                                                    _select[index]["count"]-- ;
                                                                    sum() ;
                                                                    setState(() {});
                                                                  }
                                                                },
                                                              ) ,
                                                              Container(
                                                                height: ScreenUtil().setHeight(22),
                                                                width: ScreenUtil().setWidth(20),
                                                                margin: EdgeInsets.only(left:ScreenUtil().setWidth(13) , right:ScreenUtil().setWidth(13)),
                                                                child: Center(
                                                                  child: Text(
                                                                    _select[index]["count"].toString() , style: TextStyle(
                                                                      color: Color.fromARGB(255, 19, 28, 53) ,
                                                                      fontSize: ScreenUtil().setSp(16) ,
                                                                      fontWeight: FontWeight.bold 
                                                                    ),
                                                                  ),
                                                                ),
                                                              ) ,
                                                              GestureDetector(
                                                                child: Container(
                                                                  width: ScreenUtil().setHeight(22) ,
                                                                  height: ScreenUtil().setHeight(22) ,
                                                                  color: Colors.white ,
                                                                  child: Center(
                                                                    child: Container(
                                                                      width: ScreenUtil().setHeight(18),
                                                                      height: ScreenUtil().setHeight(18),
                                                                      decoration: BoxDecoration(
                                                                        color: Color.fromARGB(255, 248, 248, 249) , 
                                                                        borderRadius: BorderRadius.all(Radius.circular(ScreenUtil().setHeight(9)))
                                                                      ),
                                                                      child: Center(
                                                                        child: Text("+" , style: TextStyle(
                                                                          color: _select[index]["count"] == _list[index]["stock"] ? Color.fromARGB(255, 205, 207, 221) : Color.fromARGB(255, 19, 28, 53) ,
                                                                          fontWeight: FontWeight.bold 
                                                                        ),),
                                                                      ),
                                                                    ),
                                                                  ) ,
                                                                ),
                                                                onTap: (){
                                                                  if(_select[index]["count"] >= _list[index]["stock"]){
                                                                    return ;
                                                                  }else{
                                                                    _select[index]["count"]++ ;
                                                                    sum() ;
                                                                    setState(() { });
                                                                  }
                                                                },
                                                              ),
                                                            ],
                                                          ),
                                                        )
                                                      )
                                                    ],
                                                  ),
                                                )
                                              ],
                                            ),
                                          ),
                                        )
                                      ],
                                    )
                                  ),
                                ),
                              ),
                              onTap: (){
                                _select[index]["select"] = !_select[index]["select"] ;
                                sum() ;
                                setState(() { });
                              } 
                            ) ;
                          }) ,
                        ),
                      ),
                    ),
                  ) ,
                  Container(
                    height: ScreenUtil().setHeight(60),
                    decoration: BoxDecoration(
                      color: Colors.white ,
                      boxShadow: <BoxShadow>[
                        BoxShadow(
                          blurRadius: 12 ,
                          color: Color.fromARGB(80 , 0, 0, 0) ,
                          offset: Offset(0 , 3)
                        )
                      ]
                    ),
                    child: Row(
                      children: <Widget>[
                        GestureDetector(
                          child: Container(
                            padding: EdgeInsets.only(left:ScreenUtil().setWidth(30)),
                            height: ScreenUtil().setHeight(90),
                            color: Colors.white ,
                            child: Row(
                              children: <Widget>[
                                Container(
                                  width: ScreenUtil().setHeight(18),
                                  height: ScreenUtil().setHeight(18),
                                  child:Image.asset(_all ? "assets/images/selected.png" : "assets/images/un_select.png" , fit: BoxFit.fill,) ,
                                ),
                                Container(
                                  margin: EdgeInsets.only(left:ScreenUtil().setWidth(5)),
                                  child: Text("全选" , style: TextStyle(
                                    fontSize: ScreenUtil().setSp(14) ,
                                    color: Color.fromARGB(255, 19, 27, 54) ,
                                    fontWeight: FontWeight.bold 
                                  ),),
                                ) ,
                              ],
                            ),
                          ),
                          onTap: (){
                            if(_all){
                              for(var i = 0 ; i < _select.length ; i++){
                                _select[i]["select"] = false ;
                              }
                              _all = false ;
                              setState(() {});
                            }else{
                              for(var i = 0 ; i < _select.length ; i++){
                                _select[i]["select"] = true ;
                              }
                              _all = true ;
                              setState(() {});
                            }
                            sum() ;
                          },
                        ) ,
                        Expanded(
                          child: Container(
                            height: ScreenUtil().setHeight(22),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end ,
                              crossAxisAlignment: CrossAxisAlignment.end ,
                              children: <Widget>[
                                Container(
                                  child: Container(
                                    child: Text("合计：" , style: TextStyle(
                                      fontSize: ScreenUtil().setSp(12) ,
                                      color: Color.fromARGB(255, 19, 28, 53) ,
                                    ),),
                                  ),
                                ) ,
                                Container(
                                  child: Container(
                                    child: Text("￥" , style: TextStyle(
                                      fontSize: ScreenUtil().setSp(12) ,
                                      color: Colors.red ,
                                      fontWeight: FontWeight.bold
                                    ),),
                                  ),
                                ) ,
                                Container(
                                  margin: EdgeInsets.only(right:ScreenUtil().setWidth(44)) ,
                                  //width: ScreenUtil().setWidth(70),
                                  child: Container(
                                    child: Text(money.toString().indexOf(".") + 3 < money.toString().length ? money.toString().substring(0 , money.toString().indexOf(".")+3) : money.toString() , style: TextStyle(
                                      fontSize: ScreenUtil().setSp(18) ,
                                      color: Colors.red ,
                                      fontWeight: FontWeight.bold 
                                    ),overflow: TextOverflow.ellipsis,),
                                  ),
                                )
                              ],
                            ),
                          ),
                        ) ,
                        GestureDetector(
                          child: Container(
                            width: ScreenUtil().setWidth(100),
                            height: ScreenUtil().setHeight(40),
                            margin: EdgeInsets.only(right:ScreenUtil().setWidth(15)),
                            decoration: BoxDecoration(
                              color: canPay ? Color.fromARGB(255, 0, 195, 206) : Color.fromARGB(255, 205, 207, 222) ,
                              borderRadius: BorderRadius.all(Radius.circular(21)) ,
                            ),
                            child: Center(
                              child: Text("去结算" , style: TextStyle(
                                fontSize: ScreenUtil().setSp(14) ,
                                fontWeight: FontWeight.bold ,
                                color:Colors.white 
                              ),),
                            ),
                          ),
                          onTap: () async{
                            if(canPay){
                              if(def == null && def != "error"){
                                def = await Navigator.of(context).push(CustomRoute(Place())) ;
                              }else if(def == "error"){
                                Toast.show("网络不给力无法生成订单", context) ;
                              }else{
                                // Navigator.of(context).push(CustomRoute(Orders(def: def,))) ;
                                _visible = true ;
                                setState(() {});
                                var data = "" ;
                                for(var i = 0 ; i < _select.length ; i++){
                                  if(_select[i]["select"]){
                                    data += _list[i]["sid"].toString()+" "+_select[i]["count"].toString()+"|" ;
                                  }
                                }
                                data = data.substring(0 , data.length - 1) ;
                                MarketService().createOrder(data).then((value){
                                  if(value["code"] == 200){
                                    Navigator.of(context).push(CustomRoute(Orders(def: def,data: value["data"],))) ;
                                    _visible = false ;
                                  }else{
                                    Toast.show(value["msg"], context) ;
                                    _visible = false ;
                                  }
                                  setState(() { });
                                }) ;
                              }
                            }
                          },
                        )
                      ],
                    ),
                  )
                ],
              ),
            ) ,
            Visibility(
              visible: _visible,
              child: Container(
                color: Colors.white ,
                child: Center(
                  child: Container(
                    height: 40,
                    child: Column(
                      children: <Widget>[
                        SizedBox(
                          width: ScreenUtil().setWidth(360),
                          height: 4,
                          child: LinearProgressIndicator(
                            backgroundColor: Colors.grey[100] ,
                            valueColor: AlwaysStoppedAnimation(Colors.grey) ,
                          ),
                        ) ,
                        Container(
                          margin: EdgeInsets.only(top:5),
                          child: Text("正在为您生成订单"),
                        )
                      ],
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  sum(){
    canPay = false ;
    money = 0 ;
    for(var i = 0 ; i < _select.length ; i++){
      if(_select[i]["select"]){
        money += _list[i]["price"]*_select[i]["count"] ;
        canPay = true ;
      }
    }
    setState(() {});
  }
}